<template>
  <a-modal
    :closable="false"
    :visible="uploadVisible"
    title="上传图片"
    okText="上传图片"
    @cancel="handleCancel"
    @ok="handleOk"
  >
    <div>
      <EditorCell editor_cell_name="图片链接" isRequired>
        <div class="input-img">
          <a-input v-model:value="url" placeholder="请输入图片的网络地址" />
          <a-button type="primary" @click="previewImage">提取</a-button>
        </div>
      </EditorCell>
      <EditorCell v-if="preivewURL" editor_cell_name="图片预览">
        <div>
          <img :src="preivewURL" alt="" class="img-preview" />
        </div>
      </EditorCell>
    </div>
  </a-modal>
</template>

<script lang='ts'>
import { defineComponent, PropType, ref } from "vue";
import EditorCell from "./editorcell.vue";
import { message } from "ant-design-vue";
export default defineComponent({
  name: "UploadImg",
  components: { EditorCell },
  props: {
    uploadVisible: {
      type: Boolean,
      default: false,
      required: true,
    },
    /** 回调函数 */
    uploadCallback: {
      type: Function as PropType<(imgurl: string) => void>,
      default: () => new Function(),
    },
  },
  setup(props, { emit }) {
    /** 图片url */
    const url = ref<string>("");
    /** 图片预览 */
    const preivewURL = ref<string>("");
    /** 点击图片预览 */
    const previewImage = () => {
      const img = new Image();
      img.setAttribute("src", url.value);
      img.onload = () => {
        preivewURL.value = url.value;
      };
    };
    const handleOk = () => {
      if(!preivewURL.value){
        message.error('请上传正确的图片!')
        return;
      }
      emit("update:uploadVisible", false);
      props.uploadCallback?.(preivewURL.value);
    };
    const handleCancel = () => {
      emit("update:uploadVisible", false);
    };
    return {
      url,
      preivewURL,
      previewImage,
      handleOk,
      handleCancel,
    };
  },
});
</script>

<style lang='scss' scoped>
.input-img {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.img-preview {
  width: 100%;
  height: auto;
}
</style>